﻿using System;
using HtmlAgilityPack;

namespace Daroctrius.WebTV
{
    public class TeleQuebecHandler : BaseHandler
    {
        private static string SiteUrl = "http://video.telequebec.tv/";

        private void AddEpisodeCategory(Items items, HtmlNode li, string url)
        {
            if (!li.Attributes["class"].Value.Contains("Disabled"))
            {
                items.Add(new Item()
                {
                    ContentUrl = String.Format("/tele-quebec.ashx?m=GetEpisodes&url={0}{1}?sortExpression=1&sortDirection=0", Request["url"], url),
                    Name = li.InnerText,
                    Type = ItemType.Folder
                }); 
            }
        }

        public Items GetEpisodeCategories()
        {
            HtmlDocument doc;
            HtmlNode categoryTabs;
            HtmlNodeCollection li;
            Items items;
            string url;

            url = SiteUrl;
            url += Request["url"];

            doc = LoadHtmlDocument(url);
            items = new Items();

            categoryTabs = doc.GetElementbyId("categoryTabs");
            li = categoryTabs.SelectNodes("li");

            if (li[0].Attributes["class"].Value.Contains("versionIntegrale")) AddEpisodeCategory(items, li[0], "/version-integrale");
            else AddEpisodeCategory(items, li[0], "/episodes-complets");

            if (li[1].Attributes["class"].Value.Contains("extraits")) AddEpisodeCategory(items, li[1], "/extraits");
            else AddEpisodeCategory(items, li[1], "/segments-d-episodes");
            
            AddEpisodeCategory(items, li[2], "/exclusivites-web");

            return items;
        }

        public Items GetEpisode()
        {
            HtmlDocument doc;
            HtmlNode videoInfoLeft, videoMoreInfo;
            Items items;
            PlayItem item;
            string location, url;
            int endIndex, startIndex;

            url = SiteUrl;
            url += Request["url"];

            doc = LoadHtmlDocument(url);
            items = new Items();

            videoInfoLeft = doc.GetElementbyId("videoInfoLeft");
            videoMoreInfo = doc.GetElementbyId("videoMoreInfo");

            foreach (HtmlNode script in doc.DocumentNode.SelectNodes("/html/head/script"))
            {
                if (script.InnerText.Contains("rtmp:"))
                {
                    startIndex = script.InnerText.IndexOf("rtmp:");
                    endIndex = script.InnerText.IndexOf(".flv", startIndex);
                    location = script.InnerText.Substring(startIndex, endIndex - startIndex);

                    endIndex = location.LastIndexOf("/");

                    item = new PlayItem();
                    item.Link = location.Substring(0, endIndex + 1);
                    item.PageUrl = url;
                    item.PlayPath = location.Substring(endIndex + 1, location.Length - endIndex - 1);
                    item.SwfUrl = "http://video.telequebec.tv/content/flash/lecteur_av_stq.swf?v1.42";

                    items.Add(new Item()
                    {
                        ContentUrl = item.ContentUrl,
                        Description = videoMoreInfo.SelectSingleNode("p").InnerText,
                        Name = videoInfoLeft.SelectSingleNode("h3").InnerText,
                        ThumbnailUrl = Request["ThumbnailUrl"],
                        Type = ItemType.PlayNowVideo
                    });
                }
            }

            return items;
        }

        public Items GetEpisodes()
        {
            HtmlDocument doc;
            HtmlNode categoryListing, listingTable, listVideoTitleAnchor, pagination, seasonNode;
            Items items;
            string name, seasonTitle, thumbnailUrl, url;
            string[] pages;
            int page;

            items = new Items();
            page = 1;

            while (true)
            {
                url = String.Format("{0}{1}&page={2}", 
                    SiteUrl, 
                    Request["url"], 
                    page);

                doc = LoadHtmlDocument(url);

                categoryListing = doc.GetElementbyId("categoryListing");
                listingTable = categoryListing.SelectSingleNode("table[@class=\"listingTable\"]");
                seasonTitle = "";

                pagination = categoryListing.SelectSingleNode("div[@class=\"listingContentBox\"]/p[@class=\"pagination\"]");
                pages = pagination.InnerText.Replace("Page", "").Trim().Split('/');                

                foreach (HtmlNode tr in listingTable.SelectNodes("tbody/tr"))
                {
                    seasonNode = tr.SelectSingleNode("th/h5[@class=\"seasonTitle\"]");

                    if (seasonNode != null)
                    {
                        seasonTitle = seasonNode.InnerText;
                    }
                    else
                    {
                        listVideoTitleAnchor = tr.SelectSingleNode("td/span[@class=\"listVideoTitle\"]/a");

                        if (!String.IsNullOrEmpty(seasonTitle))
                        {
                            name = String.Format("{0} - {1}",
                                seasonTitle,
                                listVideoTitleAnchor.InnerText);
                        }
                        else name = listVideoTitleAnchor.InnerText;

                        thumbnailUrl = tr.SelectSingleNode("td/div[@class=\"listThumb\"]/a/img").Attributes["src"].Value;

                        items.Add(new Item()
                        {
                            ContentUrl = String.Format("/tele-quebec.ashx?m=GetEpisode&url={0}&ThumbnailUrl={1}", listVideoTitleAnchor.Attributes["href"].Value, thumbnailUrl),
                            Description = tr.SelectSingleNode("td/div[@class=\"noScreenBox\"]").InnerText,
                            Name = name,
                            ThumbnailUrl = thumbnailUrl,
                            Type = ItemType.Folder
                        });
                    }
                }

                if (Int32.Parse(pages[0]) == Int32.Parse(pages[1])) break;
                page++;
            }

            return items;
        }        

        public Items GetCategories()
        {
            HtmlDocument doc;
            HtmlNode leftColDiv;
            Items items;
            
            doc = LoadHtmlDocument(SiteUrl);
            items = new Items();

            leftColDiv = doc.GetElementbyId("leftColDiv");

            foreach (HtmlNode p in leftColDiv.SelectNodes("p[contains(@class, \"navSectionTitle\")]"))
            {
                if (!p.Attributes["class"].Value.Contains("navTitleNavigation"))
                {
                    items.Add(new Item()
                    {
                        ContentUrl = String.Format("/tele-quebec.ashx?m=GetShows&xpath={0}", p.NextSibling.NextSibling.XPath),
                        Name = p.InnerText,
                        Type = ItemType.Folder
                    });                    
                }
            }

            return items;
        }

        public Items GetShows()
        {
            HtmlDocument doc;
            Items items;
            HtmlNode ol;

            doc = LoadHtmlDocument(SiteUrl);
            items = new Items();

            ol = doc.DocumentNode.SelectSingleNode(Request["xpath"]);

            foreach (HtmlNode li in ol.SelectNodes("li"))
            {
                items.Add(new Item()
                {
                    ContentUrl = String.Format("/tele-quebec.ashx?m=GetEpisodeCategories&url={0}", li.SelectSingleNode("a").Attributes["href"].Value),
                    Name = li.InnerText,
                    Type = ItemType.Folder
                });
            }

            return items;
        }
    }
}